﻿using ScFramework.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ScFramework.Core
{

    public class TypeManager : SystemModule
    {
        Dictionary<Type, Dictionary<string, string>> typeNamesDic = new Dictionary<Type, Dictionary<string, string>>();
        public override void Initialize(Main m)
        {
            base.Initialize(m);

        }
        public override void Dispose()
        {
        }

        public override void SysFixedUpdate(float deltaTime)
        {
        }

        public override void SysUpdate(float deltaTime)
        {
        }
        public void InitTypeNames<T>() where T : class
        {
            if (typeNamesDic.ContainsKey(typeof(T)))
            {
                return;
            }
            var list = ScFramework.Utilities.TypeUtilities.GetTypeNames(typeof(T));
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach(var s in list)
            {
                string ns = s.Split('.')[s.Split('.').Length - 1];
                if (dic.ContainsKey(ns))
                {
                    Debug.LogWarning($"{typeof(T)}的多个子类有相同简称");
                }
                dic[ns] = s;
            }
            typeNamesDic[typeof(T)] = dic;
        }
        /// <summary>
        /// 通过简称实例化指定基类和名称的实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public T CreatInstanceByShortName<T>(string name)where T:class
        {
            InitTypeNames<T>();
            if (typeNamesDic[typeof(T)].ContainsKey(name) == false)
            {
                Debug.LogError($"没有名为{name}的类型{typeof(T)}类");
            }
            return Activator.CreateInstance(Type.GetType(typeNamesDic[typeof(T)][name])) as T;
        }
        public List<Type> GetSubTypes(Type type)
        {
            return new List<Type> ( TypeUtilities.GetTypes(type) );
        }
    }
}